package edu.mju.eduorder.service.impl;

import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.github.wxpay.sdk.WXPayUtil;
import edu.mju.eduorder.entity.StudyOrder;
import edu.mju.eduorder.entity.StudyPayLog;
import edu.mju.eduorder.mapper.StudyPayLogMapper;
import edu.mju.eduorder.service.StudyOrderService;
import edu.mju.eduorder.service.StudyPayLogService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import edu.mju.eduorder.utils.ConstantQrCode;
import edu.mju.eduorder.utils.HttpClient;
import edu.mju.servicebase.exception.StuException;
import org.springframework.beans.NotWritablePropertyException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.math.BigDecimal;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;

/**
 * <p>
 * 支付日志表 服务实现类
 * </p>
 *
 * @author xiaoxin
 * @since 2020-10-05
 */
@Service
public class StudyPayLogServiceImpl extends ServiceImpl<StudyPayLogMapper, StudyPayLog> implements StudyPayLogService {

    @Autowired
    private StudyOrderService studyOrderService;

    /**
     * 生成微信支付二维码接口
     * @param orderNo 订单编号
     * @return Map集合
     */
    @Override
    public Map<String, Object> createNative(String orderNo) {
        try {
            //1.根据订单号查询订单信息
            QueryWrapper<StudyOrder> wrapper = new QueryWrapper<>();
            wrapper.eq("order_no",orderNo);
            StudyOrder order = studyOrderService.getOne(wrapper);

            //2.使用map设置生成二维码需要参数
            Map<String,String> map = new HashMap<>();
            map.put("appid", ConstantQrCode.WX_PAY_APP_ID);
            map.put("mch_id",ConstantQrCode.WX_PAY_MCH_ID);
            map.put("nonce_str", WXPayUtil.generateNonceStr());
            //课程名称
            map.put("body", order.getCourseTitle());
            //订单号
            map.put("out_trade_no", orderNo);
            map.put("total_fee", order.getTotalFee().multiply(new BigDecimal("100")).longValue()+"");
            //本地测试为：127.0.0.1 域名
            map.put("spbill_create_ip", "127.0.0.1");
            map.put("notify_url", ConstantQrCode.WX_PAY_NOTIFY_URL);
            map.put("trade_type", "NATIVE");

            //3.发送httpclient请求，传递xml格式，微信支付提供的固定的地址
            HttpClient client = new HttpClient(ConstantQrCode.WX_PAY_URL);
            //设置xml格式参数
            client.setXmlParam(WXPayUtil.generateSignedXml(map,ConstantQrCode.WX_PAY_PARTNER_KEY));
            client.setHttps(true);

            //执行请求发送
            client.post();

            //得到发送请求返回结果(xml格式)
            String content = client.getContent();

            //xml转换map集合
            Map<String,String> xmlMap = WXPayUtil.xmlToMap(content);

            //返回最终数据
            Map<String,Object> resultMap = new HashMap<>();
            resultMap.put("out_trade_no", orderNo);
            resultMap.put("course_id", order.getCourseId());
            resultMap.put("total_fee", order.getTotalFee());
            //返回二维码操作状态码
            resultMap.put("result_code", xmlMap.get("result_code"));
            //二维码地址
            resultMap.put("code_url", xmlMap.get("code_url"));
            return resultMap;

        }catch (Exception e){
            throw new StuException(20001,"生成二维码失败，错误如："+e.toString());
        }
    }

    /**
     * 根据订单号查询订单支付状态
     * @param orderNo 订单编号
     * @return
     */
    @Override
    public Map<String, String> queryPayStatus(String orderNo) {
        try {
            //1、封装参数
            Map map = new HashMap<>();
            map.put("appid", ConstantQrCode.WX_PAY_APP_ID);
            map.put("mch_id",ConstantQrCode.WX_PAY_MCH_ID);
            map.put("out_trade_no", orderNo);
            map.put("nonce_str", WXPayUtil.generateNonceStr());

            //2 发送httpclient
            HttpClient client = new HttpClient("https://api.mch.weixin.qq.com/pay/orderquery");
            client.setXmlParam(WXPayUtil.generateSignedXml(map,ConstantQrCode.WX_PAY_PARTNER_KEY));
            client.setHttps(true);
            client.post();

            //3 得到请求返回内容
            String xml = client.getContent();
            Map<String, String> resultMap = WXPayUtil.xmlToMap(xml);
            //6、转成Map再返回
            return resultMap;
        }catch(Exception e) {
            return null;
        }
    }

    /**
     * 支付表添加记录，更新订单表订单状态
     * @param map
     */
    @Override
    public void updateOrdersStatus(Map<String, String> map) {
        //从map获取订单号
        String orderNo = map.get("out_trade_no");
        //根据订单号查询订单信息
        QueryWrapper<StudyOrder> wrapper = new QueryWrapper<>();
        wrapper.eq("order_no",orderNo);
        StudyOrder order = studyOrderService.getOne(wrapper);

        //更新订单表订单状态
        if(order.getStatus().intValue() == 1) { return; }
        //1代表已经支付
        order.setStatus(1);
        studyOrderService.updateById(order);

        //向支付表添加支付记录
        StudyPayLog payLog = new StudyPayLog();
        //订单号
        payLog.setOrderNo(orderNo);
        //订单完成时间
        payLog.setPayTime(new Date());
        //支付类型 1微信
        payLog.setPayType(1);
        //总金额(分)
        payLog.setTotalFee(order.getTotalFee());

        //支付状态
        payLog.setTradeState(map.get("trade_state"));
        //流水号
        payLog.setTransactionId(map.get("transaction_id"));
        payLog.setAttr(JSONObject.toJSONString(map));

        baseMapper.insert(payLog);
    }
}
